import api from '@api';
import {isWechat, wechatConfig} from '@utils'
const state = {
  cate: {
    list: [],
    id: '',
    can: true
  }
}

const getters = {
  ['getCate'] (state) {
    return state.cate;
  }
}

const actions = {
   ['getCate'] ({commit, state}, wCategory) {
    if(state.cate.id == wCategory) {
      return
    } else {
      commit('clearCate')
    }
    return new Promise( async(resolve, reject) => {
      if(isWechat()) {
        await wechatConfig();
        wx.getLocation({
          type: 'wgs84',
          success: async function (res) {
            let latitude = res.latitude;
            let longitude = res.longitude;
            let {data: {warehouseList, StatusCode}} = await api.get('api/v2/Store/storeList.ashx', {latitude, longitude, wCategory});
            if(StatusCode == '200') {
              commit('setCate', {list: warehouseList, id: wCategory, can:true});
              resolve();
            }
          },
          cancel: function () {
            commit('setCate', {list: [], id: '', can: false})
            resolve();
          },
          error: function () {
            _this.locationDisable = true
          }
        });
      } else  {
        navigator.geolocation.getCurrentPosition(async function (location) {
          var latitude = location.coords.latitude;
          var longitude = location.coords.longitude;
          let {data: {warehouseList, StatusCode}} = await api.get('api/v2/Store/storeList.ashx', {latitude, longitude, wCategory});
          if(StatusCode == '200') {
            commit('setCate', {list: warehouseList, id: wCategory, can:true})
          }
          resolve()
        }, function () {
          commit('setCate', {list: [], id: '', can: false})
          resolve()
        })
      }

    })
  }
}

const mutations = {
  ['setCate'] (state, {list, id, can}) {
    state.cate.list = list;
    state.cate.id = id;
    state.cate.can = can
  },
  ['clearCate'] (state) {
    state.cate = {
        list: [],
        id: '',
        can: true
      }
  }
}

export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations
}

